<template>
  <div>
    <!-- 卡片区域 -->
    <el-card shadow="hover">
      <el-row :gutter="5">
        <!-- 分类筛选 -->
        <el-col :span="4">
          <el-select
            v-model="queryCategory.query"
            placeholder="根据分类筛选"
            @change="filterbyCategory"
            @clear="getFoodsList"
            clearable
          >
            <el-option
              v-for="item in categoryForm.categoryList"
              :key="item.id"
              :label="item.name"
              :value="item.name"
            ></el-option>
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select
            v-model="queryStatus.query"
            placeholder="根据状态筛选"
            @change="filterbyStatus"
            @clear="getFoodsList"
            clearable
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-col>
        <!-- 根据名称查询 -->
        <el-col :span="6">
          <el-input
            placeholder="请输入商品名称"
            v-model="queryInfo.query"
            @clear="getFoodsList"
            clearable
          ></el-input>
        </el-col>
        <!-- 查询按钮 -->
        <el-col :span="1">
          <el-button type="primary" icon="el-icon-search" @click="getFoodsList"
            >查询</el-button
          >
        </el-col>
        <!-- 添加商品 -->
        <el-col :span="2" :offset="7">
          <el-button icon="el-icon-plus" @click="addFoods" plain
            >添加</el-button
          >
        </el-col>
      </el-row>
    </el-card>

    <!-- 表格区域 -->
    <el-table
      :data="res"
      border
      fit
      :row-class-name="tableRowClassName"
      :header-cell-style="{ background: '#eed2d8', color: '#606266' }"
      v-loading="loading"
    >
      <el-table-column type="index" label="#" align="center"> </el-table-column>
      <el-table-column prop="imageURL" label="主图" width="61%" align="center">
        <template slot-scope="scope">
          <el-avatar
            :src="scope.row.imageURL"
            icon="el-icon-user-solid"
            shape="square"
          ></el-avatar>
        </template>
      </el-table-column>
      <el-table-column
        prop="category"
        label="分类"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="name"
        label="名称"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="priced"
        label="原价"
        align="center"
        width="80%"
      ></el-table-column>
      <el-table-column
        prop="price"
        label="现价"
        align="center"
        width="80%"
      ></el-table-column>
      <el-table-column
        prop="stock"
        label="库存"
        align="center"
        width="80%"
      ></el-table-column>
      <el-table-column prop="cover" label="设为封面" width="80%" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.cover"
            @change="changeCover(scope.row)"
            active-color="#13ce66"
            inactive-color="#C0CCDA"
            :active-value="1"
            :inactive-value="0"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="140%" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            @change="changeStatus(scope.row)"
            active-text="上架"
            inactive-text="下架"
            :active-value="1"
            :inactive-value="0"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="140%" align="center">
        <template slot-scope="scope">
          <el-button
            size="small"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            circle
          ></el-button>
          <el-button
            size="small"
            type="primary"
            icon="el-icon-edit-outline"
            @click="handleEdit(scope.row)"
            circle
          ></el-button>
          <el-button
            size="small"
            type="danger"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            circle
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑|弹出表单 -->
    <el-dialog title="编辑内容" :visible.sync="editVisible">
      <el-form :model="form" :rules="editRules">
        <el-form-item label="姓名" :label-width="formLabelWidth">
          <el-input v-model="form.nickname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" :label-width="formLabelWidth" prop="mobile">
          <el-input v-model="form.mobile" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="余额" :label-width="formLabelWidth" prop="remain">
          <el-input v-model.number="form.remain" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEdit">保 存</el-button>
      </div>
    </el-dialog>

    <!-- 页码 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 验证规则
      editRules: {
        mobile: [
          { required: true, message: '请输入电话号码' },
          { min: 11, max: 11, message: '号码长度为11位' },
        ],
        remain: [
          { required: true, message: '请输入余额' },
          { type: 'number', message: '余额必须为数字' },
        ],
      },
      // 获取用户列表的参数对象
      queryInfo: {
        query: '',
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少数据
        pagesize: 5,
      },
      // 根据分类筛选
      queryCategory: {
        query: '',
        pagenum: 1,
        pagesize: 5,
      },
      // 根据状态分类
      queryStatus: {
        query: '',
        pagenum: 1,
        pagesize: 5,
      },
      editVisible: false,
      form: {},
      formLabelWidth: '80px',
      res: [],
      total: 0,
      loading: true,
      categoryForm: {
        categoryList: [],
        name: '',
      },
      options: [
        {
          value: 1,
          label: '上架',
        },
        {
          value: 0,
          label: '下架',
        },
      ],
    }
  },
  watch: {
    $route() {
      // 对路由变化作出响应...
      this.getFoodsList()
      this.getCategory()
      this.getMonthCount()
    },
  },
  methods: {
    tableRowClassName({ rowIndex }) {
      if (rowIndex % 2 == 1) {
        return 'warning-row'
      }
      return ''
    },
    // 根据分类筛选
    filterbyCategory() {
      this.queryCategory.pagenum = this.queryInfo.pagenum
      this.queryCategory.pagesize = this.queryInfo.pagesize
      this.getFoodsLists(this.queryCategory)
    },
    // 根据状态筛选
    filterbyStatus() {
      this.queryCategory.pagenum = this.queryInfo.pagenum
      this.queryCategory.pagesize = this.queryInfo.pagesize
      this.getFoodsLists(this.queryStatus)
    },
    async getCategory() {
      const path = this.URL.Category
      const temp = []
      const { data: res } = await this.$http.get(path).catch(() => {
        return this.$message.error('NETWORK ERROR')
      })
      res.forEach((element) => {
        temp.push(JSON.parse(element))
      })
      this.categoryForm.categoryList = temp
    },
    // 公共方法
    getFoodsList() {
      this.getFoodsLists(this.queryInfo)
    },
    async getFoodsLists(query) {
      this.loading = true
      const path = this.URL.Foods
      let temp = []
      const { data: result } = await this.$http
        .get(path, {
          params: query,
        })
        .catch(() => {
          this.$message.error('NETWORK ERROR')
        })
      this.loading = false
      console.log(result)
      result.foods.forEach((element) => {
        temp.push(JSON.parse(element))
      })
      this.res = temp
      this.total = result.total
      console.log(this.res)
    },
    // 添加商品 跳转
    addFoods() {
      this.$router.push('/addfoods')
    },
    // 监听 pagesize 改变的事件
    handleSizeChange(pagesize) {
      this.queryInfo.pagesize = pagesize
      // 重新请求
      this.getFoodsList()
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(pagenum) {
      this.queryInfo.pagenum = pagenum
      // 重新请求
      this.getFoodsList()
    },
    // 查看操作
    handleView(row) {
      console.log(row)
      this.$router.push({ name: 'ViewFoods', params: row })
    },
    // 编辑操作
    handleEdit(row) {
      console.log(row)
      this.$router.push({ name: 'EditFoods', params: row })
    },
    // 保存编辑
    async saveEdit() {
      this.editVisible = false
      const path = this.URL.Foods
      const { data: res } = await this.$http
        .patch(path, {
          data: {
            id: this.form.id,
            nickname: this.form.nickname,
            mobile: this.form.mobile,
            remain: this.form.remain,
          },
        })
        .catch(() => {
          this.$message.error('NETWORK ERROR')
        })
      if (res.status !== 200) {
        this.$message.error('修改失败，请重试')
      }
      this.$message.success('保存成功')
    },
    // 删除
    async handleDelete(row) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch(() => {
        this.$message.error('NETWORK ERROR')
      })

      console.log(confirmResult, row)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除')
      }

      // delete请求
      const path = this.URL.Foods
      const { data: res } = await this.$http
        .delete(path, {
          params: { id: row.id },
        })
        .catch(() => {
          this.$message.error('NETWORK ERROR')
        })
      if (res.status !== 200) {
        return this.$message.error('删除失败')
      }
      // 删除七牛云
      const path_delete = this.URL.Upload
      await this.$http
        .patch(path_delete, {
          data: {
            key: row.imageURL,
          },
        })
        .catch((error) => error)
      this.$message.success('删除成功')
      this.getFoodsList()
    },
    // 改变状态
    async changeStatus(row) {
      console.log(row.status)
      const path = this.URL.Foods
      const { data: res } = await this.$http
        .patch(path, {
          data: {
            id: row.id,
            status: row.status,
          },
        })
        .catch(() => {
          this.$message.error('NETWORK ERROR')
        })
      if (res.status !== 200) {
        this.$message.error('操作失败，请重试!')
      } else {
        this.$message.success('操作成功')
      }
    },
    // 设为封面
    async changeCover(row) {
      // console.log(row.status)
      const path = this.URL.Foods
      const { data: res } = await this.$http
        .patch(path, {
          data: {
            id: row.id,
            cover: row.cover,
          },
        })
        .catch(() => {
          this.$message.error('NETWORK ERROR')
        })
      if (res.status !== 200) {
        this.$message.error('操作失败，请重试!')
      }
      this.$message.success('操作成功')
    },
    async getMonthCount(){
      const path = this.URL.FoodMonthCount
      const {data:res}=await this.$http
      .get(path)
      .catch(()=>{
        console.log("NETWORK ERROR")
      })
      if(res.status!==200){
        console.log("NETWORK ERROR")
      }
    }
  },
  created() {
    this.getFoodsList()
    this.getCategory()
    this.getMonthCount()
  },
}
</script>

<style lang="less" scoped>
.state {
  text-align: center;
}
</style>

<style>
.el-table .warning-row {
  background: oldlace;
}
</style>